/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package de.hsos.ai.swa.simplebookstore.control;

import de.hsos.ai.swa.simplebookstore.entity.StoreUser;
import de.hsos.ai.swa.simplebookstore.entity.UserGroup;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.apache.commons.codec.digest.DigestUtils;

/**
 *
 * @author rainer
 */
@Stateless
public class UserRepository {
    //@PersistenceContext(name="UserSecPU")
    @PersistenceContext(name="SimpleBookStorePU")
    EntityManager em;

    public UserRepository() {
    }
    
    public StoreUser addUser(String email, String password) {
        StoreUser user = new StoreUser(email, DigestUtils.sha512Hex(password), UserGroup.USER);
        em.persist(user);
        return user;
    }
    
    public StoreUser addUser(String email, String password, UserGroup group) {
        StoreUser user = new StoreUser(email, DigestUtils.sha512Hex(password), group);
        em.persist(user);
        return user;
    }
    
    public StoreUser findUserByEmail(String email) {
        return em.find(StoreUser.class, email);
    }
    
    public void removeUser(StoreUser user) {
        em.remove(user);
    }
    
    public boolean checkPasswordAgainstUser(String password, StoreUser user) {
        return DigestUtils.sha512Hex(password).equals(user.getPassword());
    }
}
